package com.heima.search.service.impl;

import com.heima.common.elasticsearch.ElasticSearchTemplate;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

    //ES组件
    @Autowired
    private ElasticSearchTemplate elasticSearchTemplate;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public ResponseResult articleSearch(UserSearchDto dto) throws IOException {

        //判空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //1.接收参数
        int pageNum = dto.getPageNum();
        int pageSize = dto.getPageSize();
        String searchWords = dto.getSearchWords();
        Date minBehotTime = dto.getMinBehotTime();

        //2.字符串搜索条件
        QueryStringQueryBuilder query = elasticSearchTemplate.getStringQueryBuilder("title", Operator.OR, "content");

        //3.日期搜索条件
        Map<String, Object> condition = new HashMap<>();
        condition.put("lt",minBehotTime);
        RangeQueryBuilder rangeQueryBuilder = elasticSearchTemplate.getRangeBuilder("publishTime", condition);

        Map<String, AbstractQueryBuilder> map = new HashMap<>();
        map.put("must", query);
        map.put("filter",rangeQueryBuilder);
        BoolQueryBuilder boolQueryBuilder = elasticSearchTemplate.getBoolQueryBuilder(map);

        //4.高亮
        //"<font style='color: red; font-size: inherit;'>title</font>"
        HighlightBuilder highlightBuilder = elasticSearchTemplate.getHighlightBuilder("title", "<font style='color: red; font-size: inherit;'>", "</font>");


        //使用ES得到数据结果
        SearchResponse search = elasticSearchTemplate.search("app_info_article", boolQueryBuilder, highlightBuilder, pageNum, pageSize, "publishTime", SortOrder.DESC);

        //处理从ES中得到的数据结果;与ES搜索结构有关,需要两次才能从数据取出
        /*{
            "host": null,
            "code": 200,
            "errorMessage": "操作成功",
            "data": [
                {
                    "layout": 1,
                    "publishTime": 1655218578000,
                    "images": "group1/M00/00/00/wKjIgl9V2CqAZe18AAOoOOsvWPc041.png",
                    "authorName": "admin",
                    "h_title": "什么是Java<font style='color: red; font-size: inherit;'>语言</font>",
                    "id": 1302862387124125698,
                    "staticUrl": "http://114.116.122.120:9000/leadnews/2022/07/16/1302862387124125698.html",
                    "authorId": 4,
                    "title": "什么是Java语言",
                    "content": "..."
                },
                {
                    "layout": 1,
                    "publishTime": 1599490862000,
                    "images": "group1/M00/00/00/wKjIgl9V2n6AArZsAAGMmaPdt7w502.png",
                    "authorName": "admin",
                    "h_title": "Java<font style='color: red; font-size: inherit;'>语言</font>跨平台原理",
                    "id": 1302864436297482242,
                    "staticUrl": "http://101.35.3.166:9000/news/2022/06/29/1541989067795771394",
                    "authorId": 4,
                    "title": "Java语言跨平台原理",
                    "content": "..."
                }
            ]
        }
        * */
        SearchHits data = search.getHits();
        SearchHit[] hits = data.getHits();

        if (hits == null) {
            return ResponseResult.okResult("");
        }

        List<Map<String, Object>> result = new ArrayList<>();
        for (SearchHit hit : hits) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();


            Map<String, HighlightField> highlightFields = hit.getHighlightFields();

            if (CollectionUtils.isEmpty(highlightFields)) {
                Text[] titles = highlightFields.get("title").getFragments();
                String join = StringUtils.join(titles, ",");
                sourceAsMap.put("h_title", join);
            }else {
                sourceAsMap.put("h_title", sourceAsMap.get("title"));
            }
            result.add(sourceAsMap);
        }

        return ResponseResult.okResult(result);
    }
}
